<style lang="less">
body{
  margin: 0px;
}
.xgpdfdata{
    padding-left: 0.5vw;
    padding-right: 0.5vw;
    width: 61vw;
    margin-left: 18.5vw;
    background: white;
}
.xgpdftreedata{
    margin-left:81vw;
    width: 12.5vw;
    background: white;
    position: fixed;
    margin-top:20vh;
    
    .titledata{
            font-size: 1.2vw;
            line-height: 3vw;
            margin-left: 1vw;
            height: 3vw;
        }
    .titletree{
        position: absolute;
        width: 12.5vw;
        padding-bottom: 0.5vw;
    }
}
    

.xgpdf{
    left:15vw;
    background: white;
    width: 61vw;
    margin: auto;
    
}

.el-dialog__header{
        margin: 0px;
        padding: 0px;
    }
    .el-dialog__body{
        margin: 0px;
        padding: 0px;
    }

</style>
<template>
  <div >
    <MainUser></MainUser>
    <div style="height:3.2vw"></div>
    <affix style="z-index: 9999;margin-top:-3.2vw">
      <MainTitle  ref="maintitle"></MainTitle>
    </affix>
    <div class="xgpdftreedata" v-if="catalogue">
        <div class="titledata" v-html="title"></div>
        <el-tree class="titletree" :data="catalogue" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
    </div>

    <div class="xgpdfdata">
        <div style="height:0.5vw;"></div>
        <!-- <div v-if="!catalogue" style="font-size:1.2vw;margin-left:0.5vw" >{{title}}</div> -->
        <div class="xgpdf">
            <div style="height:0.5vw;"></div>
            <el-row v-loading="loading" style="min-height:50vh;padding-left:0.5vw;padding-right:0.5vw">
                <el-col :span="24">
                    <div v-for="(item,i) in attachments">
                        <canvas v-for="page in item.pages" :id="i+'the-canvas'+page" :key="page" @click="dialogcavas(i,page)"></canvas>
                    </div>
                    
                </el-col>
                
            </el-row>
            <div style="height:2vw;"></div>
        </div>
        
    </div>
    
    <el-dialog   :visible.sync="canvasVisible" width="100%" fullscreen>
      <canvas :id="'canvasdiaolog'" @click="canvasVisible = false"></canvas>
    </el-dialog>
  </div>
</template>
<script>

import { test_report,assumeRole} from '@/request/api';
import MainTitle from '../main_title'
import MainUser from '../main_user'
import PDFJS from 'pdfjs-dist';
import workerSrc from 'pdfjs-dist/build/pdf.worker.entry'
PDFJS.workerSrc = workerSrc;
export default {
    data() {
        return {
            id:'',
            currentPage: 0, // pdf文件页码
            pageCount: 0, 
            numPages:0,
            catalogue:[],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            pdfUrl:'',
            loading: false,
            title:'',
            pdfDoc:null,
            pages:0,
            canvasVisible : false,
            attachments:[],
            height:window.screen.height,
        }
    },
    mounted() {
      this.id = this.$route.query.id;
      this.getAssumeRole();
    //   this.$refs.maintitle.setissousuo(false);
      
    },
    methods: {
        dialogcavas(i,num){
            this.canvasVisible = true;
            this.attachments[i].pdfDoc.getPage(num).then((page) => {
                let canvas =  document.getElementById('canvasdiaolog')
                var vp = page.getViewport({scale: 1});
                let ctx = canvas.getContext('2d')
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                console.log(vp.width);
                let viewport = page.getViewport({scale: window.innerWidth / vp.width});
                canvas.width = viewport.width * ratio
                canvas.height = viewport.height * ratio
                canvas.style.width = viewport.width + 'px'
                ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
                let renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                }
                page.render(renderContext)
            })
        },
         _renderPage (i,num) {
             
            this.attachments[i].pdfDoc.getPage(num).then((page) => {
                let canvas =  document.getElementById(i+'the-canvas' + num)
                var vp = page.getViewport({scale: 1});
                let ctx = canvas.getContext('2d')
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                console.log(vp.width);
                let viewport = page.getViewport({scale: window.innerWidth*0.7 / vp.width});
                canvas.width = viewport.width * ratio
                canvas.height = viewport.height * ratio
                canvas.style.width = '60vw'
                ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
                let renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                }
                page.render(renderContext)
                if (this.attachments[i].pages > num) {
                    this._renderPage(i,num + 1)
                }
            })
        },
        _loadFile (i,url) {
            // this.$showLoading();
            PDFJS.getDocument(url).promise.then((pdf) => {
                this.attachments[i].pdfDoc = pdf
                this.attachments[i].pages = this.attachments[i].pdfDoc.numPages
                
                this.$nextTick(() => {
                    this._renderPage(i,1);
                });
                if(i == 0){
                    this.loading = false;
                }
                if (this.attachments.length-1 > i) {
                    this.loadpdf(i+1)
                }
            });
        },
        handleNodeClick(){

        },
        //获取小概念pdf数据
        getclassiccase(){
            
            this.loading = true;
            test_report({id:this.id}).then(res => {
                if(res.ok){
                    // res.data.attachment = '/designer/Hk9d4VYg_卡诺亚橱柜技术手册 2021.08.11.pdf';
                    this.catalogue = res.data.catalogue;
                    this.title = res.data.title;
                    console.log(res.data.attachment);
                    for(let i = 0;i < res.data.attachment.length;i++){
                        let attachment = {attachment:res.data.attachment[i],pages:0,pdfDoc:null};
                        this.attachments.push(attachment);
                    }
                    if(this.attachments.length > 0){
                        var extention = this.attachments[0].attachment.split('/').pop();
                        
                        // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
                        const filename = extention
                        const response = {
                            'content-disposition': `filename=${encodeURIComponent(filename)}`
                        }
                        // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
                        const url = this.client.signatureUrl(this.attachments[0].attachment, { response });
                        this._loadFile(0,url)
                    }
                    
                    // this.loadpdf();
                }
            })
        },
        loadpdf(i){
                
                var extention = this.attachments[i].attachment.split('/').pop();
                // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
                const filename = extention
                const response = {
                    'content-disposition': `filename=${encodeURIComponent(filename)}`
                }
                // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
                const url = this.client.signatureUrl(this.attachments[i].attachment, { response });
                this._loadFile(i,url)
            
        },
        getAssumeRole(){
            assumeRole({}).then(res => {
                if(res.ok){
                    var assumedata = res.data.res;
                    let OSS = require('ali-oss');
                    this.client = new OSS({
                        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                        region: 'oss-cn-qingdao',
                        // 从STS服务获取的临时访问凭证。临时访问凭证包括临时访问密钥（AccessKeyId和AccessKeySecret）和安全令牌（SecurityToken）。
                        accessKeyId: assumedata.Credentials.AccessKeyId,
                        accessKeySecret: assumedata.Credentials.AccessKeySecret,
                        stsToken: assumedata.Credentials.SecurityToken	,
                        // 填写Bucket名称。
                        bucket: 'kny-sxy'
                    });
                    this.getclassiccase();
                }
            })
        },
        
    },
    components: {
        MainTitle,
        MainUser,
    },

}
</script>
